package com.echo.tsxStudy.localtion;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.FieldAnalysisRequest;
import org.apache.solr.client.solrj.response.AnalysisResponseBase.AnalysisPhase;
import org.apache.solr.client.solrj.response.AnalysisResponseBase.TokenInfo;
import org.apache.solr.client.solrj.response.FieldAnalysisResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

import com.echo.tsxStudy.soleDemo.JdbcTempletEcho;
import com.spatial4j.core.io.GeohashUtils;

public class SolrJTest {
	//  private static String baseUrl = "http://192.168.7.140:8080/solr/yiwei_core";  
   private static String baseUrl = "http://192.168.7.133:8888/solr/echo_core";  
   public static final SolrClient server = new HttpSolrClient.Builder(baseUrl).build();  
//集群
//String zkHostString = "zkServerA:2181,zkServerB:2181,zkServerC:2181/solr";
//SolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();
 
   /** 
    * @Description: 查询关键字 
    * </p> 
    */  
   @Test  
   public void testSoleJ(){  
       try {  
           SolrQuery query = new SolrQuery("provinceId:410000");
           query.setStart(0);
           query.setRows(30);
           query.setSort("cityCode",SolrQuery.ORDER.desc);
        //   query.setSort("city",SolrQuery.ORDER.desc);
           QueryResponse resp = server.query(query);  
          SolrDocumentList list = resp.getResults();
       //  List<SolrModel> list=    resp.getBeans(SolrModel.class);
           System.out.println(list.size());
             for (SolrDocument solrDocument : list) {
				System.out.println(solrDocument);
			}
           System.err.println(resp.getQTime());
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
   }  
   
   
   @Test
   public  void addLocationSolrJ() throws SolrServerException, IOException{
	   List<Map<String, Object> >list = new JdbcTempletEcho().queryDateTempletForList("SELECT   *  FROM erdai_api_weather_static_heweather WHERE cnty='中国'  AND  lat  BETWEEN -90 AND 90   AND lon  BETWEEN -180 AND 180   ;", null, null);
	   Collection<SolrInputDocument> collection=new ArrayList<SolrInputDocument>();
	     for (int j = 0; j < list.size(); j++) {
	    	 
	    	 SolrInputDocument doc = new SolrInputDocument();
	    	 doc.addField("id",list.get(j).get("id")); 
	    	 doc.addField("city",list.get(j).get("city")); 
	    	 doc.addField("cnty",list.get(j).get("cnty")); 
	    	 doc.addField("lat",list.get(j).get("lat")); //纬度 
	    	 doc.addField("lon",list.get(j).get("lon")); //经度
	    	 doc.addField("prov",list.get(j).get("prov")); 
	    	 doc.addField("store", list.get(j).get("lat")+","+list.get(j).get("lon")); //纬度 +","+经度
	    	  collection.add(doc);
	    	
	    	System.out.println(list.get(j));
		  }
	     server.add(collection);
         server.commit();
   }
   
    /**
     * 查询中文分词
     * @param tokenField
     * @param content
     * @return
     */
   public static List<String> getFieldDefaultAnalysis(String tokenField, String content) {  
	    FieldAnalysisRequest request = new FieldAnalysisRequest("/analysis/field");  
	    request.addFieldName(tokenField);// 字段名，随便指定一个支持中文分词的字段  
	    request.setFieldValue("");// 字段值，可以为空字符串，但是需要显式指定此参数  
	    request.setQuery(content);  
	  
	    FieldAnalysisResponse response = null;  
	    try {  
	        response = request.process(server);  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	  
	    List<String> results = new ArrayList<String>();  
	    Iterator<AnalysisPhase> it = response.getFieldNameAnalysis(tokenField).getQueryPhases().iterator();  
	    while (it.hasNext()) {  
	        AnalysisPhase pharse = (AnalysisPhase) it.next();  
	        List<TokenInfo> list = pharse.getTokens();  
	        for (TokenInfo info : list) {  
	            results.add(info.getText());  
	        }  
	    }  
	  
	    return results;  
	}  
   
     /***
      * 中文分词测试
      */
   @Test
   public  void fieldTestAnalysis(){
	    String content="空山不见人，但闻人语响。";
	   List<String> list = getFieldDefaultAnalysis("text_ik", content);
	   
	   System.out.println(list);
	   
   }
   /**
    * 
    * 基于Solr的空间搜索实战

		Solr已经提供了3种filedType来进行空间搜索：

		1）  LatLonType（用于平面坐标，而不是大地坐标）  使用本方法

		2）  SpatialRecursivePrefixTreeFieldType（缩写为RPT）

		3）  BBoxField（用于边界索引查询）
    * 
    * 
    * @throws SolrServerException
    * @throws IOException
    */
   @Test
   public  void  lbsgeobash() throws SolrServerException, IOException{
	   //百度地图：北纬 34.753488, 东经 113.631349
	   SolrQuery query = new SolrQuery();
	    query.addFilterQuery("{!geofilt}"); 
	   query.set("q", "*:*"); 
	   query.set("d","100.0"); //搜索半径 KM  精确到500M  小数点四舍五入
	   query.set("sfield","store"); //);//存储地理位置的字段名称
	   query.set("pt","34.7511150000,113.6459630000");  //  //经纬度参数格式为    纬度,经度       [   经度 X -+180 ,纬度Y  -+90】]
	   query.set("sort", "geodist() asc");//根据距离排序：由近到远
	   query.set("fl", "*,tsxjuli:geodist(),score");//到中心节点距离
	   QueryResponse rsp = server.query(query);
	   System.out.println("---查询消耗时间：-->"+rsp.getQTime());  
	   SolrDocumentList list = rsp.getResults();
       //  List<SolrModel> list=    resp.getBeans(SolrModel.class);
           System.out.println(list.size());
          for (SolrDocument solrDocument : list) {
				System.out.println(solrDocument);
			}
   }
}
